﻿using System;
using System.Threading;
using System.Web;
using System.Web.Http;
using System.Net;
using System.Web.Configuration;
using Microsoft.AspNet.SignalR;
using DashboardApp.Hubs;
using DashboardApp.DataProviders;
using DeviceModel;
using KeepAlive;

namespace DashboardApp
{
    public class WebApiApplication : HttpApplication
    {
        private Timer timerData;
 
        protected void Application_Start()
        {
            int timeoutInMs = 10000;

            try
            {
                timeoutInMs = int.Parse(WebConfigurationManager.AppSettings["DataUpdateTimeoutInSec"]) * 1000;
            }
            catch { }
            
            bool br = true;
            for (int i = 1; br; i++)
            {
                string strCategoryInfo = WebConfigurationManager.AppSettings[string.Format("Category{0}", i)];
                if (br = !string.IsNullOrEmpty(strCategoryInfo))
                {
                    var ss = strCategoryInfo.Split('/');
                    DeviceDataProvider.Instance.AddCategoriesInfo(
                        new CategoryInfo 
                            { 
                                Id = i, 
                                Name = ss[0], 
                                Description = ss[1], 
                                LowestDeviceId = int.Parse(ss[2]), 
                                HighestDeviceId = int.Parse(ss[3]) 
                            });
                }
            }

            GlobalConfiguration.Configure(WebApiConfig.Register);

            // To ignore SSL certificate check
            ServicePointManager.ServerCertificateValidationCallback = (sender, cert, chain, sslPolicyErrors) => true;

            var hubDevices = GlobalHost.ConnectionManager.GetHubContext<DevicesHub>();

            timerData = new Timer(_ => 
                {
                    hubDevices.Clients.All.AllDevices(DeviceDataProvider.Instance.Devices);

                    hubDevices.Clients.All.ServerTime(DateTime.Now.ToString());
                },
                null, 0, timeoutInMs);      
        }
        
        protected void Application_BeginRequest(object source, EventArgs e)
        {
            KeepAliveController.InitKeepAlive(source as HttpApplication);
        }
    }
}
